package com.smartfood;


import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;



public class ShakeMotionDetector implements SensorEventListener{
	private SensorManager mSensorManager;
	private Sensor mAccelerometer;
	private long lastUpdate = -1;
	private float x, y, z;
	private float last_x, last_y, last_z;
	private static final int SHAKE_THRESHOLD = 1000;

	
	public ShakeMotionDetector(Context context) {
	
		mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
		mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);

	}
	
	protected void onPauseShakeDetector() {
		mSensorManager.unregisterListener(this);
	}
	
	protected void onResumeShakeDetecor() {
		mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL);
	}
			
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// can be safely ignored for this demo
	}
	
	public void onSensorChanged(SensorEvent event) {
			
	    long curTime = System.currentTimeMillis();
	    // only allow one update every 100ms.
	    if ((curTime - lastUpdate) > 100) {
			long diffTime = (curTime - lastUpdate);
			lastUpdate = curTime;
	 
			x = event.values[0];
			y = event.values[1];
			z = event.values[2];
	
			float speed = Math.abs(x+y+z - last_x - last_y - last_z) / diffTime * 10000;
			if (speed > SHAKE_THRESHOLD) {
			    // yes, this is a shake action! Do something about it!
			//	Intent intent9=new Intent(context,RandomRecip.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				//context.startActivity(intent9);
			}
			last_x = x;
			last_y = y;
			last_z = z;
	    } 
	}

}
